package com.hkyp.ss.course.web.config;


import com.hkyp.ss.course.apis.utils.JWTTokenUtil;
import com.hkyp.ss.course.web.dto.base.ResultBean;
import com.hkyp.ss.course.web.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统拦截器
 * 1.通过token获取userId
 * 2.接口加密校验
 *
 */
@Slf4j
public class SystemInterceptor implements HandlerInterceptor {




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String host = HttpUtil.getRemoteHost(request);
        String method = request.getMethod();
        String fullUrl = HttpUtil.getFullUrl(request);
        log.info("【{}_{}_{}_Start】{}", host, method, fullUrl);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = request.getHeader("token");
        String url = request.getRequestURL().toString();
        if (url.contains("/api/")) {
            if (StringUtils.isEmpty(token)) {
                HttpUtil.printFailMessage(response,new ResultBean(401,"请登录，后访问"));
                return false;
            }
            String userId = JWTTokenUtil.getUserId(token);
            if (StringUtils.isEmpty(userId)) {
                HttpUtil.printFailMessage(response,new ResultBean(401,"无效的登录信息，请重新登录"));
                return false;
            }
            if (!JWTTokenUtil.verify(token,userId)) {
                HttpUtil.printFailMessage(response,new ResultBean(401,"登录失效，请重新登录"));
                return false;
            }
//            String ip  = JWTTokenUtil.getTokenIp(token);
//            String remoteHost = HttpUtil.getRemoteHost(request);
//            if (!Objects.equals(ip,remoteHost)) {
//                HttpUtil.printFailMessage(response,new BaseResult(401,"登录ip校验失败，请重新登录"));
//                return false;
//            }
        }
        return true;
    }
    @Override    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
